<?php

namespace addons\yunfood\model;

use addons\yunfood\library\ModelTrait;
use app\common\model\User;
use think\Db;
use think\Model;
use traits\model\SoftDelete;

/**
 * 储值订单模型
 */
class FundOrder extends Model
{
    use ModelTrait;
    use SoftDelete;

    // 表名,不含前缀
    protected $name = 'yunfood_fund_order';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = true;

    // 定义时间戳字段名
    protected $deleteTime = 'deleted_at';
    protected $updateTime = 'updated_at';
    protected $createTime = 'created_at';

    // 不显示的字段
    protected $hidden = ['deleted_at'];

    protected $resultSetType = 'collection';

    // 储值套餐数据
    public function fundPackData()
    {
        return $this->hasOne(FundPack::class, 'id', 'fund_pack_id');
    }

    // 用户数据
    public function userData()
    {
        return $this->hasOne(User::class, 'id', 'user_id');
    }

    // 支付状态
    const PAYMENT_STATUS_WAIT   = 1;
    const PAYMENT_STATUS_DONW   = 2;
    const PAYMENT_STATUS_IGNORE = 3;

    public static function getPaymentStatusList()
    {
        return [
            self::PAYMENT_STATUS_WAIT   => __('未支付'),
            self::PAYMENT_STATUS_DONW   => __('已支付'),
            self::PAYMENT_STATUS_IGNORE => __('无需支付')
        ];
    }

    public function getPaymentStatusTextAttr($value, $data)
    {
        $optionList = self::getPaymentStatusList();

        return $optionList[$data['payment_status']] ?? $data['payment_status'];
    }

    // 状态
    const STATUS_WAIT = 0;
    const STATUS_DONW = 1;

    public static function getStatusList()
    {
        return [self::STATUS_WAIT => __('未支付'), self::STATUS_DONW => __('已支付')];
    }

    public function getStatusTextAttr($value, $data)
    {
        $optionList = self::getStatusList();

        return $optionList[$data['status']] ?? $data['status'];
    }

    public static function finishOrder($orderNo, $paymentRel = 0, $paymentName = '')
    {
        Db::transaction(function () use ($orderNo, $paymentRel, $paymentName) {
            if ($fundOrder = self::where(['order_no' => $orderNo])->lock(true)->find()) {
                // 充值
                FundUser::amountCounter($fundOrder->user_id, FundRecord::ACTION_RECHARGE, $fundOrder->fund_pack_amount,
                    false, FundRecord::SOURCE_TYPE_FUND_ORDER, $orderNo);
                if ($paymentRel) {
                    $fundOrder->payment_rel = $paymentRel;
                    $fundOrder->payment_name = $paymentName;
                    $fundOrder->payment_time = time();
                    $fundOrder->payment_status = self::PAYMENT_STATUS_DONW;
                }
                $fundOrder->status = self::STATUS_DONW;
                $fundOrder->save();
            }
        });
    }
}
